Parsing String

Course- C IN LINUX >

The work involved in extracting meaning or valuable information from some kind of input string is alled “parsing”. We will now build another fun internet-callable CGI program to demonstrate the power in our hands.

#include<stdio.h>
#include<string.h>


int main(int argc, char *argv[], char *env[])
{

char *token=NULL;
char colour1[256]="";
char colour2[256]="";
int wide=0;
int high=0;
int columns=0;
int rows=0;

token =(char *) strtok(argv[1],":");
strcpy(colour1,token);

token =(char *) strtok(argv[1],":");
strcpy(colour2,token);

token =(char *) strtok(argv[1],":");
wide=atoi(token);

token =(char *) strtok(argv[1],":");
wide=atoi(token);
high=atoi(token);
printf("Content-type:text:text\html\n\n");
printf("<html>\n");
printf(<body bgcolor=\"%s\" border=2>\n",colour2);
for(rows=1; rows<=high;rows++)

{
printf("<tr>\n");

for(columns=1;columns<=wide;columns++)
{

printf("<td><h6>=%d cell=%d</h6></td>\n", rows, columns);
}
printf("</tr>\n");

}
printf("</table>\n");
printf("</body>\n");
printf("</html>\n");

return 0;

}
                   
                   

what you should see is this:

C PARSING STRING

In this program we take argv[1] which here is yellow:blue:5:5: and parse it using the library function strtok which chops the string into tokens separated by an arbitrary character ‘:’ and use these tokens as strings to specify colours and integer numbers to specify the row and cell counts of a table.

The function atoi converts an string representation of a integer to an integer (“1” to 1).

The function strtok is a little odd in that the irst time you call it with the string name you want to parse, then on subsequent calls the irst parameter is changed to NULL.

The for(…) loop mechanism was used to do something a set number of times.

The HTML terms introduced were:

<html> <body> <table> <tr> table row <td> table data cell